package com.yida.gateway.filter;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import com.yida.common.core.constant.CacheConstants;
import com.yida.common.core.constant.HttpStatus;
import com.yida.common.core.constant.TokenConstants;
import com.yida.common.core.utils.JwtUtils;
import com.yida.common.core.utils.ServletUtils;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.redis.service.RedisService;

import io.jsonwebtoken.Claims;

/**
 * 地区过滤器
 * (根据用户配置地区校验地区参数是否合法)
 *
 * @author hmh
 */
@Component
public class ValidateAreaFilter extends AbstractGatewayFilterFactory<Object>{
	
	// 排除过滤的 uri 地址，nacos自行添加
//    @Autowired
//    private IgnoreWhiteProperties ignoreWhite;
	
	@Autowired
    private RedisService redisService;
	
	@Override
	public GatewayFilter apply(Object object) {
		return (exchange, chain) -> {
			ServerHttpRequest request = exchange.getRequest();
			//由网关过滤不需要鉴权的请求。这里直接放过
			String token = getToken(request);
	        if (StringUtils.isEmpty(token))
	        {
	            return chain.filter(exchange);
	        }
	        String headAreaId = resolveBodyFromRequest(request);
	        if(StringUtils.isEmpty(headAreaId)) {
	        	return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "[W]地区编号不能为空！");
	        }
	        Claims claims = JwtUtils.parseToken(token);
	        if (claims == null)
	        {
	            return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "令牌已过期或验证不正确！");
	        }
	        String userkey = JwtUtils.getUserKey(claims);
	        boolean islogin = redisService.hasKey(getTokenKey(userkey));
	        if (!islogin)
	        {
	            return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "登录状态已过期！");
	        }
	        String userId = JwtUtils.getUserId(claims);
	        //20221206 hmh
	        String areaIds = JwtUtils.getAreaIds(claims);
	        if(!headAreaId.equals(areaIds) && !userId.equals("1")) {
	        	return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "非当前用户地区不能操作！", HttpStatus.UNAUTHORIZED);
	        }
			return chain.filter(exchange);
		};
	}
	
	private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest)
    {	
		//获取头部存放地址信息
		List<String> areaIds = serverHttpRequest.getHeaders().get("AreaId");
		if(areaIds!=null && areaIds.size()>0) {
			return areaIds.get(0);
		}
        return null;
    }
	
	/**
     * 获取缓存key
     */
    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }
	
	/**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
        {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

}
